import time
import logging

from absl import app, flags

import coin.base.database.util as db_util
import coin.support.accounting.logic.account_status_util as account_status
from xunkemgmt.support.accounting.logic.query_request import (filter_request,
                                                              get_all_requests,
                                                              select_account_request,
                                                              filter_invalid_request_and_result,
                                                              convert_to_ticker_request_list)
from coin.support.accounting.logic.memcached_importer import \
  MemcachedCoinInfoImporter as MemcachedImporter
from coin.support.accounting.logic.mysql_importer import \
  MysqlCoinInfoImporter as MysqlImporter

FLAGS = flags.FLAGS

flags.DEFINE_string('market_type', None, 'Comma separated market_type.')

flags.DEFINE_string('exchange', None, 'Comma separated exchange.')

flags.DEFINE_string('owner', None, 'Comma separated account owner.')

flags.DEFINE_string('currency', None, 'Comma separated currency. WILL BE IGNORED.')

flags.DEFINE_integer('query_frequency', 30, 'query frequency in seconds.')

flags.DEFINE_integer(
    'duration',
    None,
    'Duration for running collector in seconds. Eg. If set to 300, program will '
    'stop after running 300 seconds. If set to None, program will run forever')

flags.DEFINE_string('mysql_config', None, 'path of database config.')

flags.DEFINE_string('memcached_config', None, 'path of database config.')


def collect_tickers(request_list):
  if len(request_list) == 0:
    return

  ticker_request_list = filter_request(request_list, 
                                       filter_func=lambda x: (x.market_type, x.exchange))
  ticker_request_list = convert_to_ticker_request_list(ticker_request_list)
  ticker_response_list = account_status.query_exchange_ticker_list(ticker_request_list)
  ticker_request_list, ticker_response_list = \
    filter_invalid_request_and_result(ticker_request_list, ticker_response_list)

  db_config = db_util.read_db_config(FLAGS.memcached_config)
  importer = MemcachedImporter(db_config=db_config)
  importer.insert_ticker_history(ticker_request_list, ticker_response_list)
  # TODO(chensili): remove it after mysql back to normal
  # db_config = db_util.read_db_config(FLAGS.mysql_config)
  # importer = MysqlImporter(db_config=db_config)
  # importer.insert_ticker_history(
  #     ticker_request_list, ticker_response_list)


def main(_):
  start_time = time.time()

  request_list = get_all_requests(business_unit='Coin') + get_all_requests(business_unit='CoinFOF')
  request_list = select_account_request(request_list,
                                        market_type=FLAGS.market_type,
                                        owner=FLAGS.owner,
                                        exchange=FLAGS.exchange)
  assert len(request_list) > 0

  while True:
    collect_tickers(request_list)
    logging.info("end ticker collector")
    if FLAGS.duration is not None and \
       time.time() - start_time > FLAGS.duration:
      break
    time.sleep(FLAGS.query_frequency)


if __name__ == '__main__':
  logging.basicConfig(level='INFO', format='%(levelname)8s %(asctime)s %(message)s')
  app.run(main)
